package com.daoshu.socket.server;

import com.daoshu.socket.config.WebsocketConfig;
import com.daoshu.socket.handler.netty.WebSocketInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: NettyServer
 * @description:
 * @author: Allen
 * @create: 2019-06-24 15:32
 **/
@Slf4j
@Component
public class NettyServer {

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    @Autowired
    WebsocketConfig nettyConfig;

    @Autowired
    WebSocketInitializer webSocketInitializer;

//    @PostConstruct
    public void start() throws InterruptedException {
        log.info("starting server");
        //BOSS线程
         bossGroup = new NioEventLoopGroup();
        //Worker线程
         workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
        serverBootstrap.childHandler(webSocketInitializer);
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(nettyConfig.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

//    @PreDestroy
    public void stop() {
        log.info("stop server");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
